﻿using System;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using System.Linq;
using System.Collections.Generic;

namespace HealthCommunity.Controls
{
	public partial class UCCourseCenter : System.Web.UI.UserControl
	{
		private ICourseProvider _courseProvider;

		private List<RLT_USERANDCOURCE> _lstUserAndCourse;

		private IList<Course> _DataSource;
		private int _TotalRecords;

		public IList<Course> DataSourse
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				var selectedCrsCatItem = ddlCourseCategory.SelectedValue;

				if(!string.IsNullOrEmpty(selectedCrsCatItem))
				{
					var theCrsCatID = int.Parse(selectedCrsCatItem);

					if(_courseProvider == null)
					{
						_courseProvider = new CourseProvider();
					}

					var user = SiteContext.Current.CurrentUser;

					if(user != null && user.Role.RoleName.ToLower().Equals("admin"))
					{
						var drugstore = SiteContext.Current.CurrentDrugStore;

						if(drugstore != null)
						{
							_lstUserAndCourse = _courseProvider.GetRLTUserAndCourseByUser(user.UserID);

							_DataSource = _courseProvider.GetCourseByCategory(theCrsCatID, drugstore.DrugStoreID, pageIndex, pageSize, out totalRecords);
						}
					}
					else
					{
						if(user != null && user.DrugStoreID.GetValueOrDefault(0) > 0)
						{
							_lstUserAndCourse = _courseProvider.GetRLTUserAndCourseByUser(user.UserID);

							_DataSource = _courseProvider.GetCourseByCategory(user.UserID, theCrsCatID, user.DrugStoreID.Value, pageIndex, pageSize, out totalRecords);
						}
					}
				}

				this.TotalRecords = totalRecords;

				return _DataSource;
			}
		}

		public int PageIndex
		{
			get
			{
				if(ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = _DataSource == null ? this.DataSourse : _DataSource;

				if(data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if(totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if(totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if(totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return int.Parse(ddlPageSize.SelectedValue);
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				BindCourseCategory();
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindCourse();

			hlCreateCourse.Visible = false;
			//gvCourse.Columns[0].Visible = false;

			var u = SiteContext.Current.CurrentUser;

			if (u != null && u.Role != null)
			{
				hlCreateCourse.Visible = u.Role.RoleName.ToLower().Equals("admin") || u.Role.RoleName.ToLower().Equals("storemanager") || u.Role.RoleName.ToLower().Equals("storeadmin");
				//gvCourse.Columns[gvCourse.Columns.Count - 1].Visible = u.Role.RoleName.ToLower().Equals("storeadmin");
			}

			var currentPageIndex = this.PageIndex;
			var totalPages = TotalPages;

			// set pager index links
			List<PagerIndex> indexs = new List<PagerIndex>();

			if(totalPages <= 25)
			{
				for(int i = 1; i <= totalPages; i++)
				{
					indexs.Add(new PagerIndex(i.ToString()));
				}
			}
			else
			{
				for(var i = 13; i > 0; i--)
				{
					if(indexs.Count >= 27)
					{
						break;
					}

					var index = currentPageIndex - i;

					if(index > 0)
					{
						indexs.Add(new PagerIndex(index.ToString()));
					}
				}

				for(var i = 0; i <= 13; i++)
				{
					if(indexs.Count > 27)
					{
						break;
					}

					var index = currentPageIndex + i;

					if(index <= totalPages && index > 0)
					{
						indexs.Add(new PagerIndex(index.ToString()));
					}
				}
			}

			this.RptrPageIndex.DataSource = indexs;
			this.RptrPageIndex.DataBind();

			this.LabelTotalPages.Text = totalPages.ToString();
			this.LabelTotalRecords.Text = TotalRecords.ToString();

			// disenabel the current pagerindex link
			if(RptrPageIndex.Items.Count > 0)
			{
				for(int i = 0; i < RptrPageIndex.Items.Count; i++)
				{
					LinkButton thePagerIndexLink = RptrPageIndex.Items[i].FindControl("LBPageIndex") as LinkButton;

					if(thePagerIndexLink.Text.Trim().Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink.Enabled = false;
					}
				}
			}

			lbtnFirstPage.Enabled = (currentPageIndex > 0);

			lbtnLastPage.Enabled = totalPages > 1 && (currentPageIndex != totalPages - 1);
		}

		protected void gvCourse_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if (e.CommandName.Equals("select"))
			{
				Response.Redirect("~/CourseConfirm.aspx?courseid=" + e.CommandArgument.ToString());
			}
			else if (e.CommandName.Equals("remove"))
			{
				var theCourseID = int.Parse(e.CommandArgument.ToString());

				if (_courseProvider == null)
				{
					_courseProvider = new CourseProvider();
				}

				_courseProvider.DeleteCourse(theCourseID);
			}
		}

		protected void btnSelectCourse_Click(object sender, EventArgs e)
		{
			if (gvCourse.Rows != null && gvCourse.Rows.Count > 0)
			{
				var selectedCourseIDs = string.Empty;

				foreach (GridViewRow row in gvCourse.Rows)
				{
					var chbCourse = row.FindControl("chbCourse") as CheckBox;
					var lbtnSelect = row.FindControl("lbtnSelect") as LinkButton;

					if (chbCourse.Checked)
					{
						selectedCourseIDs += lbtnSelect.CommandArgument + " ";
					}
				}

				if (!string.IsNullOrEmpty(selectedCourseIDs))
				{
					Response.Redirect("~/CourseConfirm.aspx?courseid=" + selectedCourseIDs.Trim());
				}
			}
		}

		protected void gvCourse_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				var hlEditCourse = e.Row.FindControl("hlEditCourse") as HyperLink;
				var lbtnSelect = e.Row.FindControl("lbtnSelect") as LinkButton;
				var lblCourseName = e.Row.FindControl("lblCourseName") as Label;
				var ltrPrice = e.Row.FindControl("ltrPrice") as Literal;
				var chbCourse = e.Row.FindControl("chbCourse") as CheckBox;
				var lbtnDelete = e.Row.FindControl("lbtnDelete") as LinkButton;

				var dataItem = e.Row.DataItem as Course;

				if (dataItem != null)
				{
					if (hlEditCourse != null)
					{
						hlEditCourse.NavigateUrl = "~/CourseEdit.aspx?courseid=" + dataItem.CourseID.ToString();
					}

					if (lbtnSelect != null)
					{
						lbtnSelect.CommandArgument = dataItem.CourseID.ToString();
					}

					if (lbtnDelete != null)
					{
						lbtnDelete.CommandArgument = dataItem.CourseID.ToString();
					}

					if (_lstUserAndCourse != null && _lstUserAndCourse.Count > 0)
					{
						lbtnSelect.Enabled = (_lstUserAndCourse.Where(uc => uc.CourseID == dataItem.CourseID).Count() <= 0);
						chbCourse.Enabled = lbtnSelect.Enabled;
					}

					hlEditCourse.Visible = false;

					var u = SiteContext.Current.CurrentUser;

					if (u != null && u.Role != null)
					{
						hlEditCourse.Visible = u.Role.RoleName.ToLower().Equals("admin") || u.Role.RoleName.ToLower().Equals("storemanager") || u.Role.RoleName.ToLower().Equals("storeadmin");
						lbtnDelete.Visible = hlEditCourse.Visible;
					}

					if (dataItem.CourseName.Length > 12)
					{
						lblCourseName.Text = dataItem.CourseName.Substring(0, 12) + "...";
					}
					else
					{
						lblCourseName.Text = dataItem.CourseName;
					}
					lblCourseName.ToolTip = dataItem.CourseName;

					var price = dataItem.CourseChapters.Sum(cc => cc.CourseChapterReqiredCredits);

					ltrPrice.Text = price.GetValueOrDefault(0).ToString();
				}
			}
		}

		protected void ddlCourseCategory_SelectedIndexChanged(object sender, EventArgs e)
		{
			//BindCourse();
		}

		protected void LBPageIndex_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch(e.CommandName)
			{
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						//TotalRecords = DataSource.Count();

						BindCourse();
					}
					break;
			}
		}

		protected void lbtnFirstPage_Click(object sender, EventArgs e)
		{
			PageIndex = 0;
			BindCourse();
		}

		protected void lbtnLastPage_Click(object sender, EventArgs e)
		{
			PageIndex = TotalPages - 1;
			BindCourse();
		}

		protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.PageIndex = 0;
		}

		private void BindCourse()
		{
			var data = this.DataSourse;

			gvCourse.DataSource = data;
			gvCourse.DataBind();
		}

		private void BindCourseCategory()
		{
			if (_courseProvider == null)
			{
				_courseProvider = new CourseProvider();
			}

			var crsCats = _courseProvider.GetAllCourseCategory();
			ddlCourseCategory.DataSource = crsCats;
			ddlCourseCategory.DataBind();

			ddlCourseCategory.Items.Insert(0, new ListItem("所有课程类别", "0"));
			ddlCourseCategory.SelectedIndex = 0;
		}
	}
}